<template>
    <div class="change-password">
        <h1>添加用户</h1>
        <el-form ref="form" :model="password" :rules="rules" label-width="100px">
            <el-form-item label="旧密码" prop="old">
                <el-input v-model="password.old" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new">
                <el-input v-model="password.new" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new2">
                <el-input v-model="password.new2" type="password">
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {changePassword} from '@/api/changePassword.js'
import {removeToken} from "@/utils/auth";

export default {
    name: "ChangePassword",
    data() {
        return {
            password: {
                old: "",
                new: "",
                new2: "",
            },
            rules: {
                old: [{required: true, message: "请输入旧密码", trigger: "blur"},],
                new: [{required: true, message: "请输入新密码", trigger: "blur"}],
                new2: [{required: true, message: "请再次输入新密码", trigger: "blur"}],
            },
            loading: false
        };
    },
    methods: {
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (this.password.new != this.password.new2) {
                        this.$message.error('新密码不一致')
                        return
                    }
                    // TODO: send user data to backend
                    this.loading = true
                    //console.log(this.password);
                    changePassword(this.password.old, this.password.new).then(res => {
                        console.log(res)
                        if (res.code == 50003) {
                            this.loading = false
                            this.$message.error(res.msg)
                            return
                        }
                        this.loading = false
                        this.$refs.form.resetFields();
                        this.$message.success('修改成功')
                    }).catch(() => {
                        this.loading = false
                        this.$message.error('修改失败')
                    })

                } else {
                    console.log("form validation failed");
                }
            });
        },
        resetForm() {
            this.$refs.form.resetFields();
        },
    },
};
</script>

<style>
.add-user {
    padding: 20px;
}
</style>
